# -*- coding: utf-8 -*-
# @FileName : Goods.py
# @Time     : 2023/6/9 13:13
# @Author   : Zhong Runke
import requests
from web.controller.api import route_api
from common.models.Classify import Classify
from common.models.Goods import Goods
from flask import jsonify, request
from common.libs.Helper import getCurrentDate
from sqlalchemy.sql import or_
from common.libs.webase.WebaseService import WebaseService
from common.models.User import User
from common.models.Images import Images
from application import app, db, root_path, r
import json
import os
from common.libs.UrlManager import UrlManager


@route_api.route("/good/index", methods=["GET", "POST"])
def goodIndex():
    resp = {'code': 200, 'msg': '操作成功~', 'data': {}}
    cat_list = Classify.query.filter_by(status=1).order_by(Classify.weight.desc()).all()
    data_cat_list = []
    data_cat_list.append({
        'id': 0,
        'name': "全部"
    })
    if cat_list:
        for item in cat_list:
            tmp_data = {
                'id': item.id,
                'name': item.name
            }
            data_cat_list.append(tmp_data)
    resp['data']['cat_list'] = data_cat_list

    goods_list = Goods.query.filter_by(status=1).order_by(Goods.id.desc()).limit(3).all()

    data_food_list = []
    if goods_list:
        for item in goods_list:
            tmp_data = {
                'id':item.id,
                # 'pic_url': UrlManager.buildImageUrl( item.image )
                'pic_url': UrlManager.buildImageUrl(str(item.image))
            }
            data_food_list.append(tmp_data)

    resp['data']['banner_list'] = data_food_list
    return jsonify(resp)


@route_api.route("/good/search")
def goodSearch():
    resp = {'code':200, 'msg':'操作成功', 'data':{}}
    req = request.values
    cat_id = int(req['cat_id']) if 'cat_id' in req else 0
    mix_kw = str(req['mix_kw']) if 'mix_kw' in req else ''
    p = int(req['p']) if 'p' in req else 1

    if p < 1:
        p = 1

    page_size = 10
    offset = (p-1) * page_size
    query = Goods.query.filter_by(status=1)
    if cat_id > 0:
        query = query.filter_by(classify=cat_id)

    if mix_kw:
        rule = or_(Goods.name.ilike("%{0}%".format(mix_kw)))
        query = query.filter(rule)

    goods_list = query.order_by(Goods.id.desc()).offset(offset).limit(page_size).all()

    data_food_list = []
    if goods_list:
        for item in goods_list:
            tmp_data = {
                "id": item.id,
                "name": "%s" % (item.name),
                "price": str(item.price),
                "min_price": str(item.price),
                "pic_url": UrlManager.buildImageUrl(str(item.image))
            }
            data_food_list.append(tmp_data)
    resp['data']['list'] = data_food_list
    resp['data']['has_more'] = 0 if len(data_food_list) < page_size else 1
    return jsonify(resp)


@route_api.route('/good/release', methods=["GET", "POST"])
def goodRelease():

    if request.method == 'GET':
        resp = {'code': 200, 'msg': '操作成功', 'data': {}}
        classify_list = Classify.query.filter_by(status=1).order_by(Classify.weight.desc()).all()
        print(classify_list)
        classify_names = []
        classify_dict = {}
        for classify_info in classify_list:
            classify_names.append(classify_info.name)
            classify_dict[classify_info.name] = classify_info.id
        print(classify_names)
        print(classify_dict)
        resp['data']['classify_names'] = classify_names
        resp['data']['classify_dict'] = classify_dict
        return jsonify(resp)
    elif request.method == 'POST':
        resp = {'code':200, 'msg': '操作成功', 'data':{}}
        req = request.values
        # 登录校验
        auth_cookie = request.headers.get("Authorization") if 'Authorization' in request.headers else ''
        if not auth_cookie:
            resp['code'] = -1
            resp['msg'] = '没有Authorization'
            return jsonify(resp)
        print(auth_cookie)
        auth_info = auth_cookie.split("#")
        print(auth_info)

        # 处理数据
        detail = req['detail'] if 'detail' in req else ''
        img_str_list = req['imgList'] if 'imgList' in req else None
        imgList = img_str_list.split(",")
        try:
            price = float(req['price']) if 'price' in req else 0
        except:
            resp['code'] = -1
            resp['msg'] = '参数错误'
            return jsonify(resp)
        send_index = req['send_index'] if 'send_index' in req else -1
        classify_index = req['classify_index'] if 'classify_index' in req else -1
        user_info = User.query.filter_by(id=auth_info[-1]).first()
        if len(detail)>20:
            name = detail[:10]
        else:
            name = detail

        main_image = imgList[0].split("/")[-1]
        print(main_image)
        # 数据上链
        webase_resp = WebaseService.commonReq(user_info.address, "createGoods",
                                              [name, detail, main_image, int(price*100), classify_index],
                                              app.config['WEBASE_CONTRACTABI'],
                                              app.config['WEBASE_CONTRACTNAME'],
                                              app.config['WEBASE_CONTRACTADDRESS'])
        webase_dict = json.loads(webase_resp)
        print("=========webase_dict的id==========")
        print(webase_dict)
        print(webase_dict['message'])
        if webase_dict['message'] == 'Success':
            try:
                print("存进数据库")
                itemIdCounterStr = webase_dict['output']
                itemIdCounter = int(itemIdCounterStr, 16)
                # 将数据存进数据库
                model_good = Goods()
                model_good.name = name
                model_good.details = detail
                model_good.image = main_image
                model_good.price = price
                model_good.sendType = send_index
                model_good.classify = classify_index
                model_good.status = 1
                model_good.useraddress = user_info.address
                model_good.itemIdCounter = itemIdCounter
                model_good.blocknum = webase_dict['blockNumber']
                model_good.blockHash = webase_dict['blockHash']
                model_good.transactionhash = webase_dict['transactionHash']
                model_good.created_time = model_good.updated_time = getCurrentDate()
                # 提交
                print("提交")
                db.session.add(model_good)
                db.session.commit()

                print("==============imgList============")
                print(imgList)
                # 保存image
                for imgUrl in imgList:
                    file_key = imgUrl.split("/")[-1]
                    print(file_key)
                    model_image = Images()
                    model_image.good_id = model_good.id
                    model_image.file_key = file_key
                    model_image.created_time = getCurrentDate()
                    db.session.add(model_image)
                    db.session.commit()
            except Exception as e:
                print(e)
                resp['code'] = -1
                resp['msg'] = '数据库操作异常'
                return jsonify(resp)
        return jsonify(resp)


@route_api.route("/good/image", methods=['GET', 'POST', 'DELETE'])
def goodImage():
    print(request.method)
    if request.method == 'GET':
        resp = {'code': 200, 'msg': 'OK', 'data': {}}
        return jsonify(resp)
    elif request.method == 'POST':
        resp = {'code': 200, 'msg': 'OK', 'data': {}}
        req = request.values
        userAddress = req['userAddress'] if 'userAddress' in req else 0
        req = request.files
        file = req.get("imgfile")
        filename = file.filename
        folder_path = os.path.join(root_path + "/data/upload/")
        if not os.path.exists(folder_path):
            os.mkdir(folder_path)
        file_path = os.path.join(folder_path, filename)
        with open(file_path, 'wb') as f:
            f.write(file.read())
        print(filename)
        print(userAddress)
        print(userAddress + "#image")
        key = userAddress + "#image"
        r.lpush(key, filename)
        print("========redis===========")
        print(r.keys())
        r.expire(key, 3600)
        resp['data']['method'] = 'GET'
        return jsonify(resp)
    elif request.method == 'DELETE':
        resp = {'code': 200, 'msg': 'OK', 'data': {}}
        resp['data']['method'] = 'POST'
        req = request.values
        userAddress = req['userAddress'] if 'userAddress' in req else ''
        imgUrl = req['imgUrl'] if 'imgUrl' in req else ''
        filename = imgUrl.split("/")[-1]
        print(filename)
        name = r.lrem(userAddress + "#image", 1, filename)
        if name:
            print(name)
        return jsonify(resp)

@route_api.route("/good/info", methods=['GET', 'POST'])
def goodInfo():
    resp = {'code': 200, 'msg': 'ok', 'data': {}}
    req = request.values
    print(req)
    # 登录校验
    auth_cookie = request.headers.get("Authorization") if 'Authorization' in request.headers else ''
    if not auth_cookie:
        resp['code'] = -1
        resp['msg'] = '没有Authorization'
        return jsonify(resp)
    print(auth_cookie)
    auth_info = auth_cookie.split("#")
    print(auth_info)
    good_id = req['id'] if 'id' in req else 0
    if not good_id:
        resp['code'] = -1
        resp['msg'] = '没有该用户'
        return jsonify(resp)

    # 获取商品信息
    good_info = Goods.query.filter_by(id=good_id, status=1).first()
    # 获取商品拥有者信息
    seller_info = User.query.filter_by(address=good_info.useraddress, status=1).first()
    # 获取该商品所有图片
    images_info_list = Images.query.filter_by(good_id=good_id).all()

    seller_dict = {
        'avatar_url': UrlManager.buildImageUrl(seller_info.avatar),
        'nickname': seller_info.nickname,
        'userAddress': seller_info.address
    }
    good_dict = {
        'transactionhash': good_info.transactionhash,
        'status': good_info.status,
        'detail': good_info.details,
        'price': str(good_info.price),
        'good_id': good_info.id,
        'userAddress': good_info.useraddress
    }

    imgList = []
    for image_info in images_info_list:
        imgList.append(UrlManager.buildImageUrl(image_info.file_key))
    good_dict['imgList'] = imgList
    resp['data']['seller_info'] = seller_dict
    resp['data']['good_info'] = good_dict
    print(resp)
    return jsonify(resp)


@route_api.route('/good/grounding', methods=["POST"])
def goodGrounding():
    resp = {'code':200, 'msg':'OK', 'data':{}}
    req = request.values
    print(req)
    good_id = int(req['id']) if 'id' in req else 0
    curType = int(req['curType']) if 'curType' in req else None
    auth_cookie = request.headers.get("Authorization") if 'Authorization' in request.headers else ''
    if not auth_cookie:
        resp['code'] = -1
        resp['msg'] = '没有Authorization'
        return jsonify(resp)
    if curType is None:
        resp['code'] = -1
        resp['msg'] = '参数异常'
        return jsonify(resp)
    print(auth_cookie)
    auth_info = auth_cookie.split("#")
    print(auth_info)
    user_info = User.query.filter_by(id=auth_info[-1], status=1).first()
    print(user_info)
    if curType == 0:
        goods_info = Goods.query.filter_by(id=good_id, status=1).first()
        if not goods_info:
            resp['code'] = -1
            resp['msg'] = '没有此商品'
            return jsonify(resp)
        # 下架
        goods_info.status = 0
    elif curType == 1:
        goods_info = Goods.query.filter_by(id=good_id, status=0).first()
        if not goods_info:
            resp['code'] = -1
            resp['msg'] = '没有此商品'
            return jsonify(resp)
        # 上架
        goods_info.status = 1

    try:
        db.session.add(goods_info)
        db.session.commit()
    except:
        db.session.rollback()
        resp['code'] = -1
        resp['msg'] = '数据库操作异常'
        return jsonify(resp)
    resp['data']['curType'] = curType
    return jsonify(resp)


@route_api.route("/good/delete", methods=["POST"])
def goodDelete():
    resp = {'code': 200, 'msg': 'OK', 'data':{}}
    req = request.values
    print(req)
    good_id = int(req['id']) if 'id' in req else 0
    curType = int(req['curType']) if 'curType' in req else None
    auth_cookie = request.headers.get("Authorization") if 'Authorization' in request.headers else ''
    if not auth_cookie:
        resp['code'] = -1
        resp['msg'] = '没有Authorization'
        return jsonify(resp)
    if curType is None:
        resp['code'] = -1
        resp['msg'] = '参数异常'
        return jsonify(resp)
    print(auth_cookie)
    auth_info = auth_cookie.split("#")
    print(auth_info)
    user_info = User.query.filter_by(id=auth_info[-1], status=1).first()
    print(user_info)
    goods_info = Goods.query.filter_by(id=good_id).first()
    if not goods_info:
        resp['code'] = -1
        resp['msg'] = '没有此商品'
        return jsonify(resp)
    # 下架
    goods_info.status = -1
    try:
        db.session.add(goods_info)
        db.session.commit()
    except:
        db.session.rollback()
        resp['code'] = -1
        resp['msg'] = '数据库异常'
        return jsonify(resp)
    return jsonify(resp)


@route_api.route("/good/validation", methods=["GET", "POST"])
def good_validation():
    resp = {'code': 200, 'msg': 'OK', 'data':{}}
    req = request.values
    address = str(req['address']) if 'address' in req else None
    if not address:
        resp['code'] = -1
        resp['msg'] = '没有此商品'
        return jsonify(resp)
    print(address)
    # address = "0x6dd79ee111cbb19cb5347d99b544d9af7ce5718d682c0b15be1eb3406a8cb1a6"
    req_url = "http://120.25.1.147:5002/WeBASE-Front/1/web3/search?input={}".format(address)
    response = requests.get(req_url)
    res_json = response.json()
    print(res_json['blockHash'])
    blockHash = res_json['blockHash']
    blockNumber = res_json['blockNumber']
    print(address)
    goods_info = Goods.query.filter_by(blockHash=blockHash, transactionhash=address).first()
    if not goods_info:
        resp['code'] = -1
        resp['msg'] = '没有此商品'
        return jsonify(resp)
    status_dict = {
        "0": "在售",
        "1": "已售出",
        "2": "已下架"
    }
    data = {
        "goods_name": goods_info.name,
        "blockHash": blockHash,
        "blockNumber": blockNumber,
        "status": status_dict[str(goods_info.status)],
        "created_time": goods_info.created_time.strftime("%Y-%m-%d %H:%M:%S")
    }
    resp['data'] = data
    return jsonify(resp)